<?php

/*
 * Created on 2013-1-16
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

if (!isset($_FILES['Filedata'])) {
    exit('FILES 不存在');
}

/** MGTV节目单导入主体方法
 * @param String 
 * @return 错误描述
 * 			成功为"success"
 */
function cyyy_import_playbill() {
    $fileParts = pathinfo($_FILES['Filedata']['name']);

    if (strtolower($fileParts['extension']) == 'txt') {
//		导入文件为TXT 则调用TXT解析
        $state = cyyy_import_playbill_by_txt();
    } elseif (strtolower($fileParts['extension']) == 'xls') {
//		导入文件为EXCEL 则调用EXCEL解析
        $state = cyyy_import_playbill_by_excel();
    } else {
        $state = 'Error';
    }

    return $state;
}

/* * 解析TXT并写入数据库的方法的方法写这里。。。。* */

function cyyy_import_playbill_by_txt() {

	$tempFile = $_FILES['Filedata']['tmp_name'];
    $fileArr = file($tempFile);
    //$Channel = trim(str_replace('Channel:', '', array_shift($fileArr))); //Channel:CCTV-1
    $list = array();
    $deltime = array();
    $key = '';
    $is_continue = false;
    
    foreach ($fileArr as $k=>$v) {
    	$v = trim($v);
        if (empty($v)){
            continue;
        }
        
        $v = iconv('gbk', 'utf-8', $v);
        $v = trim($v);
     	preg_match('/([\d]{2})\/([\d]{1,2})\/([\d]{1,2})/', $v, $day);
        if(count($day)==4){
        	$key = '20'.$day[1].'-'.$day[2].'-'.$day[3].' '; // 某一天
        	$deltime[] = $key;
        	$is_continue = false;
        	continue;
        }elseif($is_continue){
        	continue;
        }
        
     	preg_match('/([\d]+):([\d]+)[\s]+([^\s]+)/', $v, $item);
     	if(count($item)!=4){
     		continue;
     	}
     	
     	if($item[3]=='结束'){
        	$is_continue = false;
        	continue;
     	}
     	$startime = $item[1].':'.$item[2].':'.'00'; // 节目开始时间
     	
     	if(isset($fileArr[$k+1])){
	     	preg_match('/([\d]+):([\d]+)[\s]+([^\s]+)/', $fileArr[$k+1], $eitem);
	     	
	     	if(count($eitem)!=4){
     			$endtime = '23:59:59';
	     	}else{
	     		$endtime = $eitem[1].':'.$eitem[2].':00'; // 节目结束时间
	     	}
     	}else{
     		$endtime = '23:59:59';
     	}
     	
     	$begin_time = $key.' '.$startime;
     	$end_time = $key.' '.$endtime;
     	$time_len = strtotime($end_time)-strtotime($begin_time);
     	if($time_len<0){
     		$is_continue = true;
     		$time_len += 3600*24;
     	}
     	
        $list[] = array(
        	'name'=>$item[3],
        	'begin_time'=>$begin_time,
        	'time_len'=>$time_len
        );
        
    }
    
    $result = mgtv_add_playbill($list, $deltime);
    return $result;
}

/* * 解析EXCEL的方法并写入数据库的方法写这里。。。。* */

function cyyy_import_playbill_by_excel() {
    require_once dirname(dirname(dirname(__FILE__))) . '/models/excel_reader/reader.php';
    $excel_reader = new Spreadsheet_Excel_Reader();
    $excel_reader->setOutputEncoding('utf-8'); //CP936
    $excel_reader->setRowColOffset(0);
    $excel_reader->read($_FILES['Filedata']['tmp_name']);
    $count_sheetData = count($excel_reader->sheets[0]['numRows']);
    $list = $excel_reader->sheets[0]['cells'];
    $result = array();
    $deltime = array();
    foreach ($list as $v) {
        $begin_time = str_replace('.', '-', $v[1]); //2013.03.29 19:30:00
        $addarr = array();
        $deltime[] = date('Ymd', strtotime($begin_time));
        $addarr['name'] = $v[0];
        $addarr['begin_time'] = $begin_time;
        $addarr['time_len'] = strtotime(str_replace('.', '-', $v[2])) - strtotime($begin_time);
        $result[] = $addarr;
    }
    $deltime = array_unique($deltime);
     
    $result = mgtv_add_playbill($result, $deltime);
    return $result;
}

/*
 * 根据导入数据 写入数据库
 */

function mgtv_add_playbill($list, $deltime) {

    if (!is_array($list) || !is_array($deltime)) {
        return false;
    }
    set_time_limit(300);
    $dc = nl_get_dc(array(
        'db_policy' => NL_DB_WRITE,
        'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
    ));
    $dc->open();
    $file_name = $_FILES['Filedata']['name'];
    $file_name = substr($file_name, 0, strrpos($file_name, '.'));
    $file_info = explode('__', $file_name);
    $video_name = $file_info[0];
    
    // 修改了频道id yyp修改开始
    if(!empty($file_info[1]))
    {
    	$info = substr($file_info[1], 0, strrpos($file_info[1], '.'));
   		$pro_id = $file_info[0];
    }
    
    //yyp修改结束
    //$live_list = nl_live_bo::get_video_ids_by_pid($dc->db(), $pro_id);
    $live_list = nl_live_bo::get_video_ids_by_name($dc->db(), $video_name);
     
    set_time_limit(300);
    /*
      if ($live_list===FALSE || $live_list===TRUE) { 判断语句有误。。。。
      return '该频道不存在！';
      } */
    //empty($pro_id)
    if (!is_array($live_list)) {
        return '该频道不存在！';
    }
    $resultnum = 0;
    foreach ($live_list as $live_item) {
        //$video_id = $live_item['nns_live_id'];
        $video_id = $live_item['nns_id'];
        foreach ($deltime as $dt) {
            $endtime = date('Ymd', strtotime($dt) + 86400);
            nl_playbill_item::del_playbill_item_info_by_time($dc, $dt, $endtime, $video_id);
        }
        
        foreach ($list as $sql) {
            if (nl_playbill_item::add_playbill_item($dc, $video_id, $sql)) {
                $resultnum++;
            }
        }
    }

    if ($resultnum > 0)
        return 'Success Count:'.$resultnum;
    else
        return '导入失败';
}
?>
